home *** CD-ROM | disk | FTP | other *** search
- Path: teal.csn.net!not-for-mail
- From: thads@csn.net (Thad Smith)
- Newsgroups: comp.std.c
- Subject: Re: Help, best way to compare doubles
- Date: 17 Jan 1996 01:51:23 -0700
- Organization: T3 Systems
- Message-ID: <mlK/wQ9ytpDN084yn@csn.net>
- References: <4d1k09$aqq@mercury.IntNet.net> <4dbos6$o7q@umbc9.umbc.edu>
- <4ddev4$1vg@stingray.mcnc.org>
- Reply-To: ThadSmith@acm.org
- NNTP-Posting-Host: 199.117.27.22
-
- In article <4ddev4$1vg@stingray.mcnc.org>,
- coats@mcnc.org (Carlie Coats) wrote:
-
- >>14.5: What's a good way to check for "close enough" floating-point
- >> equality?
-
- > A safer test is of the form
- >
- > | a - b | / sqrt( a^2 + b^2 + delta ) < epsilon
-
- This criteria, plus the squared version which uses squares, seems
- to be too much effort with no payback.
-
- Considering that the point of evaluating the approximate magnitude of
- the numbers being compared is only to make a judgement of whether two
- numbers are approximately the same, and that the decision point is
- only close for two numbers that are approximately the same, evaluating
- a square root or sum or squares buys nothing. How about
- (abs(a)+abs(b))/2? The factor 2 can be absorbed in the epsilon, just
- as well as the similar factor sqrt(2) that applies to the quoted
- expression.
-
- >or (equvalently, but in decently-efficient C):
- >
- > ( t = a - b )*t < esquared * ( a*a + b*b + delta )
- >
- >The choice of esquared == delta == 1e-20 gives this a
- >colloquial English meaning of
- >
- > "a and b agree to about 10 significant digits"
- >
- >which is a reasonable version of "are approximately equal"
- >for doubles.
-
- Besides the undefined nature pointed out by Tanmoy, we need to be
- careful here in equating esquared and delta because they
- perform different functions. While esquared is closely related to the
- number of matching significant digits, delta allows the relative
- difference to become larger as the magnitude of numbers get smaller.
- Using the values above, when the magnitude of the two numbers are less
- than 1e-20 and of the same sign, then the relative difference may be
- ANYTHING and the near-equality test will pass. This will probably be
- overly restrictive or insufficiently restrictive, depending on the
- general magnitudes of the numbers involved.
-
- The biggest problem, I think, in using such a criteria is in
- understanding the proper limits to be applied. If we are working with
- 3-digit data, a 10-digit derived value is almost certainly overkill.
-
- Thad
-
-